﻿using com.tanlingyun.DbServices;
using com.tanlingyun.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace com.tanlingyun.Baojia.Controllers
{
    /// <summary>
    /// 数据导入
    /// </summary>
    [UserType(type = new com.tanlingyun.ViewModel.ELevelType[] { ViewModel.ELevelType.Admin,ViewModel.ELevelType.Manager })]
    public class ImportDataController : BaseController
    {
        /// <summary>
        /// 数据导入界面
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public JsonResult Upload(HttpPostedFileBase file)
        {
            if (file == null || file.ContentLength == 0)
                return ErrorResult(ViewModel.ResultCode.Failed,"未获取到文件");
            if (file.ContentType != "application/octet-stream" && file.ContentType != "application/vnd.ms-excel")
                return ErrorResult(ViewModel.ResultCode.Failed,"暂时只支持格式为xls的office excel 2003");

            if (!System.IO.Directory.Exists(Server.MapPath("/") + "Upload/"))
                System.IO.Directory.CreateDirectory(Server.MapPath("/") + "Upload/");

            string relativePath = "Upload/"+Guid.NewGuid().ToString().Replace("-","");
            file.SaveAs(Server.MapPath("/") + relativePath);
            return SuccessResult<string>(relativePath);
        }

        /// <summary>
        /// 解析文件
        /// </summary>
        /// <param name="file"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public JsonResult AnalyseData(string file,int type)
        {
            if (string.IsNullOrWhiteSpace(file) || type == 0)
                return ErrorResult(ViewModel.ResultCode.Failed,"未获取到数据!");
            OperateResult result = null;
            switch (type)
            {
                case (int)EImportType.Raw:
                    RawService _rawService = new RawService();
                    result = _rawService.AnalysisRawData(entityUser.id, file);
                    break;
                default:
                    break;
            }
            if (result != null && result.code == ResultCode.Success)
                return SuccessResult();
            else if (result != null)
                return ErrorResult(result.code, result.message);
            return ErrorResult(ResultCode.Failed, "文件解析失败！");
        }
    }
}